package com.rr.config;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author RR
 * @date 2023/1/18 16:22
 */

/*
* 自定义断言工厂
* 1. 断言工厂名字设置
*     后缀固定为：RoutePredicateFactory
*     前缀为自己配置，这里是：DiyCheck
*     搭配3diyPredicateFactory配置文件食用
* 2. 继承AbstractRoutePredicateFactory类
* 3. 类中设置静态内部Config类，用来接收配置的参数，记得配getter和setter方法
* 4. 重写List<String> shortcutFieldOrder()方法，映射静态内部Config类的字段名
* 5. 重写Predicate<ServerWebExchange> apply(Config config)方法，用来自定义断言逻辑
* 6. 重写下构造方法，直接super即可
* 7. 把类注册到spring容器中
* */
@Component
public class DiyCheckRoutePredicateFactory extends AbstractRoutePredicateFactory<DiyCheckRoutePredicateFactory.Config> {

    public DiyCheckRoutePredicateFactory(){
        super(Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String port = String.valueOf(serverWebExchange.getRequest().getURI().getPort());
                return port.equals(config.getPort1()) || port.equals(config.getPort2());
            }
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("port1","port2");
    }

    @Validated
    public static class Config{
        private String port1;
        private String port2;

        public String getPort1() {
            return port1;
        }

        public void setPort1(String port1) {
            this.port1 = port1;
        }

        public String getPort2() {
            return port2;
        }

        public void setPort2(String port2) {
            this.port2 = port2;
        }
    }
}
